<template>
  <div class="page-container">
    <div class="form-container">
      <el-form
        :inline="true"
        label-suffix=""
        :label-width="'100px'"
        :size="'small'"
        ref="form"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="收付类别">
              <el-select v-model="state.query.isIncome">
                <el-option label="全部" value=""></el-option>
                <el-option label="应收" :value="1"></el-option>
                <el-option label="应付" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算单位" label-width="100px">
              <el-select
                v-model="state.query.entId"
                placeholder="请选择结算单位"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getBusDetail"
                :loading="state.settlementLoading"
              >
                <el-option
                  v-for="item in state.settlementList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right">{{ item.entFullname }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="对方账户">
              <el-input
                v-model="state.query.bankAccount"
                clearable
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种">
              <el-select
                v-model="state.query.currency"
                placeholder="请选择币种"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getCurrentData"
                :loading="state.currentLoading"
              >
                <el-option
                  v-for="item in state.current"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left"> {{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="账单时间">
              <el-date-picker
                v-model="sailTime"
                type="daterange"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                size="small"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="[
                  new Date(2000, 1, 1, 0, 0, 0),
                  new Date(2000, 1, 1, 23, 59, 59),
                ]"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账单编号">
              <el-input
                v-model="state.query.balanceDoccode"
                clearable
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="账单状态">
              <el-select
                v-model="state.query.checkStatus"
                placeholder="请选择账单状态"
                style="width: 100%"
                filterable
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="草拟" :value="0"></el-option>
                <el-option label="待对账" :value="1"></el-option>
                <el-option label="已驳回" :value="-1"></el-option>
                <el-option label="已对账" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-select
                v-model="state.query.createUser"
                placeholder="请选择业务员"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getSalesman"
                :loading="state.salesmanLoading"
              >
                <el-option
                  v-for="item in state.salesman"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="flex-container">
          <el-button type="primary" icon="search" @click="getList" size="small">
            搜索
          </el-button>
          <el-button type="info" icon="refresh" @click="reset" size="small">
            重置
          </el-button>
        </div>
      </el-form>
    </div>
    <div class="in-container" style="margin-top: 8px">
      <div class="btn-box">
        <el-button type="default" icon="RefreshRight" @click="getList">
        </el-button>
        <el-button type="primary" @click="createBill"> 创建账单 </el-button>
        <el-button type="primary" @click="submitBill(1)"> 提交对账 </el-button>
        <el-dropdown
          ref="dropdown1"
          trigger="hover"
          style="margin-left: 10px; margin-right: 10px"
          @command="submitBill"
        >
          <el-button type="primary">
            确认对账<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="2">完成对账</el-dropdown-item>
              <el-dropdown-item :command="-1">驳回对账</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- @update:option="upDataOption" -->
      <AppPageTable
        stripe
        :data="state.tableData.data"
        @change="getList"
        :height="525"
        :option="state.tableData.option"
        v-loading="state.tableLoading"
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        />
        <el-table-column
          prop="doctype"
          label="收付类别"
          align="center"
          showOverflowTooltip
        >
          <template #default="scope">
            <span class="inText" v-if="scope.row.doctype == 1">应收</span>
            <span class="outText" v-if="scope.row.doctype == 0">应付</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="entFullname"
          align="center"
          label="结算单位"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="bankAccount"
          width="120px"
          label="对方账号"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="doccode"
          label="账单编号"
          align="center"
          showOverflowTooltip
        >
          <template #default="scope">
            <el-button type="text" @click="toDetail(scope.row)">{{ scope.row.doccode }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="docstatus"
          label="账单状态"
          align="center"
          showOverflowTooltip
        >
          <template #default="scope">
            {{ scope.row.docstatus == 0 ? "草拟" : scope.row.docstatus == 1 ? "待对账" : scope.row.docstatus == 2 ? "已对账" : "已驳回" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currencyCode"
          align="center"
          label="账单币种"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="money"
          align="center"
          label="账单金额"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="invoiceMoney"
          align="center"
          label="发票金额"
          showOverflowTooltip
        >
        </el-table-column>

        <el-table-column
          prop="verificationMoney"
          label="已销金额"
          align="center"
          showOverflowTooltip
        >
        </el-table-column>

        <el-table-column
          prop="createTime"
          width="100"
          align="center"
          label="账单日期"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.createTime
                ? $utils.formatDateTime(scope.row.createTime, "YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          showOverflowTooltip
          fixed="right"
        >
          <template #default="scope">
            <el-button type="text" v-if="scope.row.docstatus != 2" @click="toDetail(scope.row)">完善</el-button>
          </template>
        </el-table-column>
      </AppPageTable>
      <!-- 创建账单 -->
      <el-dialog
        v-model="state.show"
        title="创建账单"
        width="520px"
        modal-class="modify-invoice-dailog"
        @close="modfiyClose"
      >
        <el-form
          ref="modfiyFormRef"
          label-suffix="："
          label-width="80px"
          size="small"
          :model="state.modfiyForm"
          :rules="state.modfiyRules"
        >
          <el-form-item label="账单编号" prop="doccode">
            <el-input
              v-model="state.modfiyForm.doccode"
              placeholder="请输入"
              style="width: 100%"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="收付类型" prop="doctype">
            <el-select v-model="state.modfiyForm.doctype">
              <el-option label="应收" :value="1"></el-option>
              <el-option label="应付" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="结算单位" prop="entId">
            <el-select
              v-model="state.modfiyForm.entId"
              placeholder="请选择结算单位"
              style="width: 100%"
              clearable
              filterable
              remote
              :remote-method="getBusDetail"
              :loading="state.settlementLoading"
              @change="getAccount"
            >
              <el-option
                v-for="item in state.settlementList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right">{{ item.entFullname }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="对方账户" prop="bankAccount">
            <el-select
              v-model="state.modfiyForm.bankAccount"
              placeholder="请选择对方账户"
              style="width: 100%"
              clearable
              filterable
              remote
              @change="AccountChange"
            >
              <el-option
                v-for="item in state.modfiyAccountList"
                :key="item.id"
                :label="item.bankAccount"
                :value="item.bankAccount"
              >
                <span style="float: left">{{ item.bankAccount }}</span>
                <span style="float: right">{{ item.bankName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="button-container">
            <el-button type="default" @click="state.show = false"
              >取消</el-button
            >
            <el-button type="primary" @click="modifySubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed,toRaw } from "vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import request from "@/public/request";
import dayjs from "dayjs";
import { MoreFilled, ArrowDown } from "@element-plus/icons";
import { fileDownload } from "@/public/publicUtils";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const Router = useRouter();

const state = reactive({
  // 查询条件
  query: {
    isIncome: "", //收付类别
    entId: "", //结算单位
    bankAccount: "", //对方账户
    currency: "", //帐单币种
    createTime: [], //账单时间
    balanceDoccode: "", //账单编号
    createUser: "", //业务员
    checkStatus: null, //账单状态 0 草拟 1 待对账 2 已对账 3 已驳回
  },
  //表格数据
  tableData: {
    data: [],
    option: useTableOption(),
  },
  tableLoading: false,
  // 展开
  hidden: false,
  // 结算对象的数据
  settlementList: [],
  settlementLoading: false,
  // 币种
  current: [],
  // 业务员
  salesman: [],
  salesmanLoading: false,

  // 币种数组
  curList: [],
  currentLoading: false,
  show: false,
  // 发票修改信息
  modfiyForm: {
    doccode: "",
    doctype: "",
    entId: "",
    entFullname: "",
    bankAccount: "",
  },
  modfiyAccountList: [],
  modfiyRules: {
    doccode: [{ required: true, message: "账单编号不可为空", trigger: "blur" }],
    doctype: [{ required: true, message: "请选择收付类别", trigger: "blur" }],
    entId: [{ required: true, message: "请选择结算单位", trigger: "blur" }],
    bankAccount: [
      { required: true, message: "请选择对方账号", trigger: "blur" },
    ],
  },
});

// 账单时间
const sailTime = computed({
  get: function () {
    return [state.query.createTime[0], state.query.createTime[1]];
  },
  set: function (val) {
    if (val) {
      state.query.createTime[0] = val[0];
      state.query.createTime[1] = val[1];
    } else {
      state.query.createTime[0] = "";
      state.query.createTime[1] = "";
    }
  },
});

// 创建账单
const createBill = async () => {
  let res = await request.get(
    "/api/bucode/doccodeSerialByCode?code=SYS_BALANCE_I"
  );
  state.modfiyForm.doccode = res;
  state.show = true;
};
// 提交对账
const submitBill = async (val) => {
  if (!state.tableData.option.selected.length) {
    ElMessage.warning('请选择数据')
    return
  }
  let req = {
    ids: [],
    checkStatus: val
  }
  let flagOfSubmit = true
  for (const iterator of state.tableData.option.selected) {
    if (val == 1) {
      if (iterator.docstatus > 0) {
        flagOfSubmit = false
        ElMessage.error('只能提交草稿或者驳回状态的数据')
        break
      }

      
    } else if (val == 2) {
      if (iterator.docstatus != 1) {
        flagOfSubmit = false
        ElMessage.error('只能审核提交状态的数据')
        break
      }
    } else if (val == -1) {
      if (iterator.docstatus < 1) {
        flagOfSubmit = false
        ElMessage.error('只能驳回通过、提交的数据')
        break
      }
    }
    req.ids.push(iterator.id)
  }
  if (!flagOfSubmit) {
    return
  }
  let res = await request.post('/api/docbalance/checkBalanceStatus', req)
  if (res.status) {
    getList()
    ElMessage.success('成功')
  } else {
    ElMessage.warning(res.message)
  }
}
const modfiyFormRef = ref();

// 获取对方账户
const getAccount = async (val) => {
  if (val) {
    let arr = state.settlementList.filter(i=>{
      return i.value == val
    })
    state.modfiyForm.entFullname = arr[0].entFullname;
    let res = await request.get("/api/buenterprisebank/query", {
      Entld: val,
    });
    state.modfiyAccountList = res;
    if (res.length != 0) {
      state.modfiyForm.bankAccount = res[0].bankAccount;
    }
  } else {
    state.modfiyAccountList = [];
    state.modfiyForm.bankAccount = "";
  }

  modfiyFormRef.value.validateField('entId');
  modfiyFormRef.value.validateField('bankAccount');
};
const AccountChange = () => {
  modfiyFormRef.value.validateField('bankAccount');
}


// 创建账单提交
const modifySubmit = async () => {
  let valid = await modfiyFormRef.value.validate();
  if (valid) {
    let res = await request.post("/api/docbalance/createBalance", {
      id: 0,
      ...state.modfiyForm,
    });
    if (res.status) {
      ElMessage.success("成功");
      getList();
      state.show = false;

      Router.openTab({
        path: "/finance/FeeBillDetail",
        query: {
          id: res.data.id,
          title: `账单详情${res.data.doccode}`,
          iscopy: false,
        },
      });
    } else {
      ElMessage.warning(res.message);
    }
  }
};
const modfiyClose = () => {
  modfiyFormRef.value.resetFields();
}
// 完善账单
const toDetail = (row) => {
  Router.openTab({
    path: "/finance/FeeBillDetail",
    query: {
      id: row.id,
      title: `账单详情${row.doccode}`,
      iscopy: false,
    },
  });
};

// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true;
  let res = await request.get("/api/base/currency/dropdownlist", {
    keywords: val,
  });
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + "|" + item.currencyName,
      value: item.currencyCode,
    };
  });
  state.currentLoading = false;
};

// 获取列表数据
const getList = async () => {
  let search = {
    PageIndex: state.tableData.option.page,
    PageSize: state.tableData.option.pageSize,
    ...state.query,
  };
  state.tableLoading = true;
  let res = await request.post("/api/docbalance/GetBalanceList", search);

  state.tableData.data = res.content;
  state.tableData.option.total = res.totalElements;
  state.tableLoading = false;
};

// 重置
const reset = () => {
  state.query = {
    isIncome: "", //收付类别
    entId: "", //结算单位
    bankAccount: "", //对方账户
    currency: "", //帐单币种
    createTime: [], //账单时间
    balanceDoccode: "", //账单编号
    createUser: "", //业务员
    checkStatus: null, //账单状态 0 草拟 1 待对账 2 已对账 3 已驳回
  };
  getList();
};

// 获取结算对象的数据
const getBusDetail = async (val) => {
  state.settlementLoading = true;
  let res = await request.get("/api/buenterprise/dropdownlist", {
    KeyWords: val,
  });
  res.forEach((item) => {
    item.label = item.entCode;
    item.value = item.id;
  });
  state.settlementList = res;
  state.settlementLoading = false;
};

// 获取业务员
const getSalesman = async (val) => {
  state.salesmanLoading = true;
  let res = await request.get("/api/user/userList", {
    keyword: val,
  });
  res.forEach((item) => {
    item.label = item.username;
    item.value = item.username;
  });
  state.salesman = res;
  state.salesmanLoading = false;
};

onMounted(()=>{
  getList();
})
</script>

<style lang="scss" scoped>
.form-container {
  border: 1px solid #e8e8e8;
  padding: 6px 6px 6px 8px;
  background-color: #ffffff;

  :deep(.el-form-item--small .el-form-item__label) {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.85);
  }

  :deep(.el-input--suffix .el-input__inner) {
    padding-right: 4px;
  }

  :deep(.el-form--inline .el-form-item) {
    display: flex;
    margin-right: 0;
  }

  :deep(.el-form-item--small.el-form-item) {
    margin-bottom: 8px;
  }
}

.in-container {
  height: auto;
}

.btn-box {
  margin-bottom: 8px;
}

.flex-container {
  display: flex;
}

.statistical-results {
  padding-left: 20px;
  padding-right: 20px;

  .statistical-tip {
    display: inline-block;
    background: #2867c9;
    width: 4px;
    height: 20px;
    vertical-align: middle;
    margin-left: -20px;
  }

  .statistical-label {
    margin: 0 16px;
    display: inline-block;
    font-weight: 600;
    color: #000000a6;
  }

  .statistical-text {
    color: red;
    font-size: 12px;
    line-height: 18px;
  }
}

.doccode-text {
  color: rgb(24, 144, 255);
  cursor: pointer;
}

.button-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.inText {
  color: #9b0000d8;
}
.outText {
  color: #00b807d8;
}
</style>

<style lang="scss">
.modify-invoice-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
  }
}

</style>
